<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mainpage extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct() {
		parent::__construct();
		$this->load->model('weibo_model');
		session_start();
	}
	public function index()
	{
                    //$temp=$this->session->userdata('access_token');
					$temp=$_SESSION['token']['access_token'];
                    
                    $c = new SaeTClientV2( WB_AKEY , WB_SKEY ,$temp );
                    $ms  = $c->home_timeline(); // done
                    $uid_get = $c->get_uid();
                    $uid = $uid_get['uid'];
                    $user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
                    
                    $query_user_info = $this->db->get_where('user', array('uid' => $uid));   //查询数据库里是否有该用户信息
                    //$query_user_info=$this->db->query($sql);
                    $user_info=$query_user_info->result_array();
                    
                    if(empty($user_info))  //如果user数据表里【没有】当前登录的用户
                    {
                            $this->weibo_model->set_user_info($uid,$user_message['screen_name'],$user_message['profile_image_url']);

                            //获取双向关注用户列表
                            $mutual_fans=$c->bilateral_ids($uid);

                            //如果互粉好友多于或等于5个则随机抽取5个互粉好友，否则存储所有的互粉好友
                            $fans_rows=($mutual_fans['total_number']<=5)?$mutual_fans['ids']:(array_rand($mutual_fans['ids'], 5));

                            //将5个互粉好友信息和最新微博存入数据表weibo中
                            if($mutual_fans['total_number']<=5)
                            {
                                    foreach($fans_rows as $item)
                                    {
                                            $user=$c->show_user_by_id($item);

                                            $fans_screen_name=$user['screen_name'];  //用户昵称
                                            $fans_img_url=$user['profile_image_url'];   //头像链接
                                            $created_at=$user['status']['created_at'];   //博文发布时间
                                            $text=$user['status']['text'];   //博文内容
                                            if( isset ($user['status']['retweeted_status']))  //如果有原创微博，即互粉用户发的非原创微博
                                            {
                                                    $retweeted_uid=$user['status']['retweeted_status']['user']['id'];
                                                    $retweeted_screen_name=$user['status']['retweeted_status']['user']['screen_name'];
                                                    $retweeted_created_at=$user['status']['retweeted_status']['created_at'];
                                                    $retweeted_txt=$user['status']['retweeted_status']['text'];
                                            }
                                            else
                                            {
                                                    $retweeted_uid='';
                                                    $retweeted_screen_name='';
                                                    $retweeted_created_at='';
                                                    $retweeted_txt='';
                                            }
                                            $this->weibo_model->set_weibo_info($user_message['id'],$item,$fans_screen_name,$fans_img_url,$created_at,$text,$retweeted_uid,$retweeted_screen_name,$retweeted_created_at,$retweeted_txt);
                                    }
                            }
                            else
                            {
                                    foreach($fans_rows as $item)
                                    {
                                            $user=$c->show_user_by_id($mutual_fans['ids'][$item]);   //由array_rand()随机取出的是关联数组的key，此处需要转化成value

                                            $fans_screen_name=$user['screen_name'];  //用户昵称
                                            $fans_img_url=$user['profile_image_url'];   //头像链接
                                            $created_at=$user['status']['created_at'];   //博文发布时间
                                            $text=$user['status']['text'];   //博文内容
                                            if( isset ($user['status']['retweeted_status']))  //如果有原创微博，即互粉用户发的非原创微博
                                            {
                                                    $retweeted_uid=$user['status']['retweeted_status']['user']['id'];
                                                    $retweeted_screen_name=$user['status']['retweeted_status']['user']['screen_name'];
                                                    $retweeted_created_at=$user['status']['retweeted_status']['created_at'];
                                                    $retweeted_txt=$user['status']['retweeted_status']['text'];
                                            }
                                            else
                                            {
                                                    $retweeted_uid='';
                                                    $retweeted_screen_name='';
                                                    $retweeted_created_at='';
                                                    $retweeted_txt='';
                                            }
                                            $this->weibo_model->set_weibo_info($user_message['id'],$mutual_fans['ids'][$item],$fans_screen_name,$fans_img_url,$created_at,$text,$retweeted_uid,$retweeted_screen_name,$retweeted_created_at,$retweeted_txt);
                                    }
                            }  //endif 根据互粉好友数目判断用户信息入库方式
                    }//endif 新账户入库
                    
                    //从数据库读出微博信息并显示在前端页面上
					//$sql="select * from weibo where uid=$uid";
					//$query=$this->db->query($sql);
                   $query=$this->db->get_where('weibo', array('uid' => $uid));
                   $weibo_info=$query->result_array();
				   //var_dump($weibo_info);
                   
                    //读取信息返回到view(mainpage)
                    $pattern_url="/(http:\/\/[a-zA-Z0-9.\/]+)/";  //匹配短链接的正则表达式
                    $pattern_at="|(@[\x{4e00}-\x{9fa5}A-Za-z0-9_]+)|u";        //匹配@某用户的正则表达式

                    //微博内容中@和短链接的解析，必须先解析短链接再解析@，次序不能颠倒，如果先解析@，解析短链接的时候会
                    //把已解析好的@内容给解析掉

                    //将读取的5条微博里的短链接转化成超链接
                    foreach ($weibo_info as &$item)
                    {
                        if(preg_match_all($pattern_url, $item['text'], $matches,PREG_PATTERN_ORDER))  //如果能找到短链接
                        {
                            foreach($matches[0] as $match)   //将该微博内容中的每一条短链接转化成超链接
                            {
                                $replace="<a style='text-decoration:none'  target='_blank' href=".$match.">".$match."</a>";    //完整的超链接
                                $item['text']=str_replace($match, $replace, $item['text']);   //用超链接替换博文中的短链接
                            }
                        }
                    }

                    //如果是非原创微博，则将原微博中的短链接也转化成超链接
                    if( ! empty($weibo_info['retweeted_uid']))
                    {
                        foreach ($weibo_info as &$item) 
                        {
                            if(preg_match_all($pattern_url, $item['retweeted_txt'], $matches,PREG_PATTERN_ORDER))
                            {
                                foreach($matches[0] as $match)
                                {
                                    $replace="<a style='text-decoration:none' target='_blank' href=".$match.">".$match."</a>";
                                    $item['retweeted_txt']=str_ireplace($match, $replace, $item['retweeted_txt']);
                                }
                            }
                        }
                    }//解析短链接结束

                    //将读取的微博中有@到某一用户的信息转化成超链接
                    foreach($weibo_info as &$item)
                    {
                        if(preg_match_all($pattern_at, $item['text'], $matches,PREG_PATTERN_ORDER))  //如果存在@信息
                        {
                            foreach($matches[0] as $match)   //将该微博内容中的每一条@信息接转化成超链接
                            {
                                $name=strtok($match, "@");  //将用户昵称识别出来
                                //$user_infomation=$c->show_user_by_name( $name );   //以用户昵称为参数调用接口获取用户信息
								$replace="<a class='at' name='$name'>@".$name."&nbsp</a>";    //完整的超链接
                                $item['text']=str_replace($match, $replace, $item['text']);   //用超链接替换博文中的@信息
                            }
                        }
                     }
                    if( ! empty($weibo_info['retweeted_uid']))
                    {
                        foreach($weibo_info as &$item)
                        {
                            if(preg_match_all($pattern_at, $item['retweeted_txt'], $matches,PREG_PATTERN_ORDER))  //如果存在@信息
                            {
                                foreach($matches[0] as $match)   //将该微博内容中的每一条@信息接转化成超链接
                                {
                                    $name=strtok($match, "@");  //将用户昵称识别出来
                                    //$user_infomation=$c->show_user_by_name( $name );   //以用户昵称为参数调用接口获取用户信息
									$replace="<a class='at' name='$name'>@".$name."&nbsp</a>";    //完整的超链接
                                    $item['retweeted_txt']=str_replace($match, $replace, $item['retweeted_txt']);   //用超链接替换博文中的@信息
                                }
                            }
                         }
                    }//解析@结束
                    
                    $data['user_message']=$user_message;
                    $data['ms']=$ms;
                    $data['user_info']=$weibo_info;
                    $data['c']=$c;
                    $data['uid_me']=$uid;
		//$this->load->view('weiboapp/mainpage_view',$data);
                    $this->load->view('weiboapp/weibo_fans',$data); 
	}
}
/* End of file mainpage.php */
/* Location: ./application/controllers/mainpage.php */
